<?php
namespace app\admin\controller;

use Think\Db;
use think\Request;
use think\Config;
use app\api\model\Privatechat;
use GatewayClient\Gateway;

class Service extends Common
{
    public function index()
    {
        $where['t1.delete_time'] = 0;

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if($search_type == 'user_id'){
                $where['t1.' . $search_type] = $search_name;
            }else{
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.create_time'] = ['elt', strtotime($end)];
        }

        $state = input('state');
        if ($state || $state === '0') {
            $this->assign('state', $state);
            $where['t1.state'] = $state;
        }

        $data = Db::name('user_service')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id', 'left')
            ->where($where)
            ->field('t1.*, t2.name, t2.head_portrait')
            ->order('t1.is_top desc, t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['category_name'] = Db::name('labels')->where(['id' => ['in', $item['category']]])->column('name');
                $item['category_name'] = implode(' ', $item['category_name']);
                if (!$item['image']) {
                    $item['image'] = $item['head_portrait'];
                }
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function watch($id)
    {
        $content = Db::name('user_service')->where(['id'=>$id])->value('content');
        echo $content;
    }

    public function addIndex(Request $request)
    {
        echo 12345;
    }

    public function delIndex(Request $request)
    {

    }

    public function stateIndex(Request $request)
    {

    }

    public function category()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            $where['t1.' . $search_type] = ['like', "%$search_name%"];
        }

        $data = Db::name('category_of_service')
            ->alias('t1')
            ->join('category_of_service t2', 't1.tid = t2.id', 'left')
            ->where($where)
            ->field('t1.*, t2.title as p_title')
            ->select();

        $this->assign('data', $data);
        return $this->fetch();
    }

    public function addCategory(Request $request)
    {
        $cate = Db::name('category_of_service')
            ->alias('t1')
            ->join('category_of_service t2', 't1.tid = t2.id', 'left')
            ->field('t1.*, t2.title as p_title')
            ->select();

        $this->assign('category', getCate($cate));

        $id = $request->param('id');
        if($id){
            $name = Db::name('category_of_service')->where('id', $id)->find();
            $this->assign('name', $name);
        }

        if($request->isAjax()){
            $data = $request->param();

            if(!$data['title']){
                return ['err' => '请填写分类名称'];
            }
            $timenow = time();
            if(!$id){ // 添加
                $result = Db::name('category_of_service')->insert([
                    'title' => $data['title'],
                    'tid' => $data['tid'],
                    'des' => $data['des'],
                    'icon' => $data['icon'],
                    'create_time' => $timenow,
                    'update_time' => $timenow,
                ]);
                $msg  = '添加';
            }else{ //编辑
                $result = Db::name('category_of_service')->where(['id' => $data['id']])->update([
                    'title' => $data['title'],
                    'tid' => $data['tid'],
                    'des' => $data['des'],
                    'icon' => $data['icon'],
                    'update_time' => $timenow,
                ]);
                $msg  = '修改';
            }

            if($result){
                return ['ret' => $msg . '成功'];
            }
            return ['err' => $msg . '失败'];
        }

        return $this->fetch();
    }

    public function delCategory(Request $request)
    {
        $id = $request->param('id');
        $cate = Db::name('category_of_service')->where('tid', $id)->field('id')->find();
        if($cate){
            return ['err' => '有子集，不能被删除'];
        }

        if(Db::name('category_of_service')->delete($id)){
            return ['ret' => '删除成功'];
        }
        return ['err' => '删除失败'];
    }

    public function order()
    {
        $paymethod = (array)Config::get('field.paymethod');
        $paystate = Config::get('field.paystate');
        $orderstate = Config::get('field.orderstate');
        $orderstatus = Config::get('field.orderstatus');


        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if($search_type == 'user_id'){
                $where['t1.' . $search_type] = $search_name;
            }else{
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $where['t1.create_time'] = ['elt', strtotime($end)];
        }
        
        $paystate = input('paystate/d', 0);
        if ($paystate) {
            $paystates = [1, 0];
            $where['t1.paystate'] = $paystates[$paystate - 1];
        }
        $this->assign('paystate', $paystate);
        $status = input('status/d', 0);
        if ($status) {
            $statuses = [0,1,2,-1,-1];
            $where['t1.status'] = $statuses[$status - 1];
            if ($status == 5) {
                $where['t1.state'] = -4;
            } else {
                $where['t1.state'] = 0;
            }
        }
        $this->assign('status', $status);
        $paystatename = ['已失效', '待支付', '已付款'];
        $paymethodname = ['未发起支付', '金币', '支付宝', '微信'];
        $data = Db::name('order_of_service')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id')
            ->join('user t3', 't1.shopowner = t3.id')
            ->field('t1.*, t2.name, t3.name as shopowner_name')
            ->order('t1.create_time desc')
            ->where($where)
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) use ($paymethodname, $paystatename, $orderstate, $orderstatus) {
                $item['paymethod_name'] = $paymethodname[$item['paymethod']];
                $item['paystate_name'] = $paystatename[$item['paystate'] + 1];
                $item['orderstate_name'] = $item['state'] == 0 && $item['status'] == -1 ? '售后中' :$orderstate[$item['state']];
                $item['orderstatus_name'] = $orderstatus[$item['status']];
                $item['volley'] = $item['price'] * 5;
                $item['method'] = json_decode($item['data'], true)['method'] ?? 2;
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addOrder(Request $request)
    {

    }

    public function setStatus($id)
    {
        $status = input('status');
        $order = Db::name('order_of_service')->where(['id'=>$id, 'paystate'=>1,'state'=>0,'status'=>['<>', 2]])->find();
        if(!$order){
            return ['ret' => '操作失败'];
        }
        if ($status == -4) {
            $res = Db::name('order_of_service')->where(['id'=>$id])->update(['state'=>-4]);
            if($res){
                $free = Db::name('privatechat_free')->where(['order_sn'=>$order['number']])->find();
                $timenow = time();
                $update = ['end_time'=>$timenow];
                if ($free['start_time'] == 0) {
                    $update['start_time'] = $timenow;
                }
                Db::name('privatechat_free')->where(['order_sn'=>$order['number']])->update(['end_time'=>time()]);


                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $order['shopowner']]));
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['shopowner'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $order['user_id']]));
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/order/orderCount']));
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $order['shopowner'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/order/orderCount']));

                return ['ret' => '操作成功'];
            }
        } else {
            $res = Db::name('order_of_service')->where(['id'=>$id])->update(['status'=>$status]);
            if($res){
                if ($status == 2) {
                    Db::name('privatechat_free')->where(['order_sn'=>$order['number'],'start_time'=>0])->update(['start_time'=>time()]);
                    Db::name('privatechat_free')->where(['order_sn'=>$order['number']])->where('end_time=0 or end_time>'.time())->update(['end_time'=>time()]);
                }
                return ['ret' => '操作成功'];
            }
        }
        return ['err' => '操作失败'];
    }
    public function delOrder($id)
    {
        $order = Db::name('order_of_service')->where(['id'=>$id])->find();
        if ($order['paystate'] == 1 && $order['state'] == 0 && $order['status'] != 2) {
            return ['err' => '当前订单不可删除'];
        }
        $res = Db::name('order_of_service')->where(['id'=>$id])->delete();
        if($res){
            return ['ret' => '删除成功'];
        }
        return ['err' => '删除失败'];
    }

    public function shenhe($id, $shenhe, $reason = '')
    {
        $time = time();
        $service = Db::name('user_service')->where(['id'=>$id])->find();
        $result = Db::name('user_service')->where(['id'=>$id])->update(['state' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
        if ($result) {
            switch ((int)$shenhe) {
                case -1:
                    Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再发布", '');
                    Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>2]);
                    break;
                case 0:
                    Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】重新审核中", '');
                    Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>2]);
                    break;
                case 1:
                    Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】审核通过", '');
                    Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>1]);
                    break;
            }
            $service_tags = Db::name('user_service')->master()->where(['user_id' => $service['user_id'], 'state' => 1, 'delete_time' => 0])->column('category');
            $service_tags = implode(',', array_unique(explode(',', implode(',', $service_tags))));
            Db::name('user')->where(['id' => $service['user_id']])->update(['service_tags' => $service_tags]);
            return ['ret' => '操作成功'];
        } else {
            return ['err' => '操作失败'];
        }
    }


    public function shenheAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $shenhe = input('type');
            $reason = '';
            $time = time();
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $userids = [];
                foreach ($post as $k => $id) {
                    $service = Db::name('user_service')->where(['id'=>$id])->find();
                    $userids[] = $service['user_id'];
                    if ($shenhe == 'del') {
                    } else {
                        switch ((int)$shenhe) {
                            case -1:
                                Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再发布", '');
                                Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>2]);
                                break;
                            case 0:
                                Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】重新审核中", '');
                                Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>2]);
                                break;
                            case 1:
                                Privatechat::notice($service['user_id'], "您发布的服务【".$service['title']."】审核通过", '');
                                Db::name('dymanic')->where(['source_type'=>3,'source_id'=>$id])->update(['shenhe'=>1]);
                                break;
                        }
                    }
                }

                if ($shenhe == 'del') {
                    Db::name('user_service')->where(['id'=>['in', $post]])->delete();
                } else {
                    $result = Db::name('user_service')->where(['id'=>['in', $post]])->update(['state' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
                }
                $userids = array_unique($userids);

                foreach ($userids as $key => $value) {
                    $service_tags = Db::name('user_service')->master()->where(['user_id' => $value, 'state' => 1, 'delete_time' => 0])->column('category');
                    $service_tags = implode(',', array_unique(explode(',', implode(',', $service_tags))));
                    Db::name('user')->where(['id' => $value])->update(['service_tags' => $service_tags]);
                }
                $data = ['ret' => '操作成功'];
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    public function categoryEdit()
    {
        $id = input("id");
        $t = db('labels')->where('parent_id', 0)->order('sort desc,id asc')->select();
        $checkeddb = db('user_service')->where('id', $id)->value('category');
        $checkeddb = $checkeddb ? explode(',', $checkeddb) : [];
        $html = '';
        foreach ($t as $k => $v) {
            $html .= '<h5>' . $v['name'] . ' ['. ($v['service_type'] == 1 ? '线下' : '线上') . ']</h5>';
            $html .= '<div class="form-group">';
            $html .= '<div class="col-sm-10">';
            $html .= '<div class="radio i-checks">';
            $t2 = db('labels')->where('parent_id', $v['id'])->order('sort desc,id asc')->select();
            if ($t2) {
                foreach ($t2 as $v2) {
                    $checked = '';
                    if ($id) {
                        if ($checkeddb) {
                            foreach ($checkeddb as $cv) {
                                if ($cv == $v2['id']) {
                                    $checked = 'checked';
                                    break;
                                }
                            }
                        }
                    }
                    $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v2['id'] . '" name="data[]">' . $v2['name'] . '</label>';
                }
                $html .= '</div></div></div>';
            }
        }
        $this->assign('labels', $html);
        if (request()->isAjax()) {

            $post = input('post.');;
            if (!input('?post.data')) {
                $dataname = false;
            } else {
                $dataname = $post['data'];
            }
            if ($dataname) {
                $cate = implode(',', $dataname);
                $db = db('user_service')->where('id', $id)->update(['category' => $cate]);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ['err' => '最少选一个类别'];
            }
        } else {
            $data = $this->fetch();
        }
        return $data;
    }

    public function zhiding($id, $state)
    {
        $res = Db::name('user_service')->where(['id'=>$id])->update(['is_top'=>$state]);
        if($res){
            return ['ret' => '操作成功'];
        }
        return ['err' => '操作失败'];
    }
}
